<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>axios取消请求</title>
    <link
      crossorigin="anonymous"
      href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2 class="page-header">axios取消请求</h2>
      <button class="btn btn-primary">发送请求</button>
      <button class="btn btn-warning">取消请求</button>
    </div>
    <script>
      // 获取按钮
      btns = document.querySelectorAll("button");

      // 2.声明全局变量
      let cancel = null;
      // 发送请求
      btns[0].onclick = function () {
        // 检测上一次请求是否已经完成
        if (cancel !== null) {
          // 上一次请求还未结束
          cancel(); // 取消上一次的请求
        }
        axios({
          method: "GET",
          url: "http://localhost:3000/posts",
          // 1.添加配置对象的属性
          cancelToken: new axios.CancelToken(function (c) {
            // 3.将c的值赋值给cancel
            cancel = c;
          }),
        }).then((response) => {
          console.log(response);
          // 将cancel的值初始化设置
          cancel = null;
        });
      };

      // 绑定第二个事件 取消请求
      btns[1].onclick = function () {
        cancel();
      };
    </script>
  </body>
</html>
